package com.ray.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ray.bean.DutyBean;
import com.ray.bean.ProductionExceptionBean;
import com.ray.bean.WeiXinPeopleBean;
import com.ray.mapper.DingTalkMapper;
import com.ray.mapper.OrderMapper;
import com.ray.mapper.WeiXinPeopleMapper;
import com.ray.mapper.WorkshopMapper;
import com.ray.service.AttendanceService;
import com.ray.service.ScheduleService;
import com.ray.service.TestService;
import com.ray.service.UserService;
import com.ray.service.WeChatToMessageService;
import com.ray.service.WeiXinService;
import com.ray.util.MailUtil;
import com.ray.util.RedirectUrlUtil;
import com.ray.util.RequestUtil;
import com.ray.util.ResponseUtil;
import com.ray.util.TimeAndUnix;
import com.ray.util.WeiXinParamesUtil;
import com.ray.util.WeiXinUtil;
import com.ray.util.picUtil.PicUtils;
import com.ray.util.weixin.WeixinTemplateList;
import com.ray.util.weixin.WeixinTemplateSender;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/test")
public class TestController {
	@Autowired
	TestService testService;
	@Autowired
	WeiXinService weiXinService;
	@Autowired
	ScheduleService scheduleService;
	@Autowired
	WorkshopMapper workshopMapper;
	@Autowired
	UserService userService;
	@Autowired
	WeiXinPeopleMapper weiXinPeopleMapper;
	@Autowired
	WeChatToMessageService weChatToMessageService;
	@Autowired
	OrderMapper orderMapper;
	@Autowired
	AttendanceService attendanceService;
	@Autowired
	DingTalkMapper dingTalkMapper;
	
	@RequestMapping("/test")
	@ResponseBody
	public String test(HttpServletRequest request) {
		Map<String, Object> requestMap = RequestUtil.getRequestParamByGeneric(request);
		//scheduleService.sendPendingApprovalMessage();
		//com.alibaba.fastjson.JSONObject data=WeixinTemplateList.packJsonToApplyStatus("申请批复通知", "已同意", "李四、王五", "2015.12.03", "你们去现场协助一下", null, null, null, null, null);
		//WeixinTemplateSender.sendWechatmsgToUser("o_THqw9VP81Ut137qpajF1u79zgA", "YZ-XYrfpgePDfNxSxQRrnzPiy35C_ypXi8Iwe3enbiQ", "https://www.baidu.com?1=1", data, "24_i0F-wz0dunGWvaon4eGCvKirufHLGdfUCd6wUKjk4roDrU-aWv_zrTx0fvd-w-TDLUAawkxiJcPba16Cx8alunnEjZEuzRw2wPto0rPDi5tZAD_r1O96uDhoSA3w2VjcWdjbTBbfnIR7j07MHDXhACACYS");
		
		attendanceService.updateDailySalaryRecord("2020-04-30","2020-04-30","龙腾科技",3810);//* 通过记录里的月薪、工时修改每日工资明细
		//attendanceService.updateDailySalaryRecord("2020-03-29","2020-03-30","龙腾科技",3804);//* 通过记录里的月薪、工时修改每日工资明细
		//scheduleService.companyTimeOut();
		/**
		 * 通过现在的月薪、工作排班修改每日工资明细
		 * @param startDate 开始日期
		 * @param endDate 结束日期
		 * @param company 公司
		 * @param personId 用户id
		 * @param groupId 考勤组id
		 * @author 王荣
		 */
		//attendanceService.updateDailySalaryRecord("2019-04-01","2019-04-22","和隆眼镜厂",2622,61);
		//获取所有用户openId
		/*List<WeiXinPeopleBean> list = weiXinPeopleMapper.getWeiXinPeopleByUserIdList(null);
		//获取相应的unionId
		String accessToken = weiXinService.getAccessToken(null);
		for(int i=0;i<list.size();i++) {
			String url="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+list.get(i).getOpenid()+"&lang=zh_CN";
			String json=WeiXinUtil.httpRequest(url);
			System.out.println(url);
			System.out.println(json);
			JSONObject jsonObject=JSONObject.fromObject(json);
			if(jsonObject.get("unionid")!=null) {
				WeiXinPeopleBean weiXinPeopleBean = list.get(i);
				weiXinPeopleBean.setUnionid(jsonObject.get("unionid").toString());
				weiXinPeopleMapper.updateWeiXinPeople(weiXinPeopleBean);
			}
		}*/
		//更新相应的unionId
		Map<String, Object> map = new HashMap<>();
    	//map.put("clockStartTime", df.format(calendar.getTime()));//昨天
    	//map.put("clockEndTime", df.format(new Date()));//今天
    	//map.put("clockStartTime", "2019-07-20");//昨天
    	//map.put("clockEndTime", "2019-07-21");//今天
    	//查询昨天和当前数据
    	//List<Map<String, Object>> list = dingTalkMapper.getInvalidClockTime(map);
		//scheduleService.generateDailyPayrollRecord();
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM");
		return simpleDateFormat.format(new Date());
	}
	
	@RequestMapping("/testssg")
	@ResponseBody
	public String testssg(HttpServletRequest request) throws IOException {
		return PicUtils.getBase64EncodeUTF8(request, 
				"/weixin/temp",
				"https://upload.shinehao.com.cn/202003051041501.jpg", 
				600, 600, ".jpg");
	}
	
	@RequestMapping("/testSetDept")
	@ResponseBody
	public Map<String,Object> testSetDept(HttpServletRequest request) throws ParseException {
		Map<String, Object> requestMap = RequestUtil.getRequestParamByGeneric(request);
		requestMap.put("startDate", "2019-03-01");
		requestMap.put("endDate", "2019-04-01");
		/*requestMap.put("deptIds", null);
		requestMap.put("userIds", null);
		requestMap.put("workshopIds", null);*/
		return ResponseUtil.ResponseResult(attendanceService.getMonthSummaryByDeptAndWorkshop(requestMap));
	}
	
	@RequestMapping("/updateProdure")
	@ResponseBody
	public void updateProdure() {
		testService.updateProdure();
	}
	
	
	@RequestMapping("/updateWorkShop")
	@ResponseBody
	public void updateWorkShop() {
		testService.updateWorkShop();
	}
	
	@RequestMapping("/testSort")
	@ResponseBody
	public void testSort() {
		scheduleService.updateFinishOrderSortMethod();
	}
	
	
	@RequestMapping("/updateChiCun")
	@ResponseBody
	public void updateChiCun() {
		testService.updateChiCun();
	}
	
	@RequestMapping("/sendMessage")
	@ResponseBody
	public void sendMessage() {
		testService.testSendMessage("119");
	}
	
	
	
	
	
	@RequestMapping("/getTimerDelaySendMessage")
	@ResponseBody
	public void  getTimerDelaySendMessage(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String dateString=sdf.format(new Date());
		List<ProductionExceptionBean>  xx=workshopMapper.getTimerDelaySendMessage();
		List<ProductionExceptionBean>  yy=workshopMapper.getSoonDelaySendMessage();
		 for(ProductionExceptionBean pp:yy) {
			 List<String> userIdList=weChatToMessageService.getWeChatNewsUserIdListByParam(pp.getCompany(), pp.getDeptId(), pp.getWorkShopId(), "2");
			 if(userIdList != null && userIdList.size()>0) {
				 List<WeiXinPeopleBean> weiXinPeopleList=weiXinPeopleMapper.getWeiXinPeopleByUserIdList(userIdList);
				 if(weiXinPeopleList != null && weiXinPeopleList.size()>0) {
					 List<DutyBean> listDuty=pp.getListDuty();
					 String soonDelay="";
					 if(listDuty==null || listDuty.size()<=0) {
						 soonDelay="恭喜您，本车间没有即将拖期的订单";
					 }else{
						 soonDelay="三天内即将拖期的订单数："+listDuty.size();
					 }
					 for(WeiXinPeopleBean weiXinPeopleBean:weiXinPeopleList) {
						 scheduleService.sendMessageUtilByOpenId(pp.getWorkShopName()+"车间即将拖期订单", weiXinPeopleBean,  "三天内将拖期异常", dateString, soonDelay, RedirectUrlUtil.workshopDelay);
					 }
				 }
			 }
		 }
		 
	    for(ProductionExceptionBean pp:xx) {
	    	 List<String> userIdList=weChatToMessageService.getWeChatNewsUserIdListByParam(pp.getCompany(), pp.getDeptId(), pp.getWorkShopId(), "2");
			 if(userIdList != null && userIdList.size()>0) {
				 List<WeiXinPeopleBean> weiXinPeopleList=weiXinPeopleMapper.getWeiXinPeopleByUserIdList(userIdList);
				 if(weiXinPeopleList != null && weiXinPeopleList.size()>0) {
					 List<DutyBean> listDuty=pp.getListDuty();
					 int three=0;
					 int four=0;
					 String soonDelay="";
					 if(listDuty==null || listDuty.size()<=0) {
						 soonDelay="恭喜您，本车间没有拖期的订单";
					 }else{
						 for(DutyBean duty:listDuty) {
							 if(duty.getDelayDay()>=3) {
								 four++;
							 }else {
								 three++;
							 }
						 }
						 soonDelay="拖期三天内订单数："+three+"   拖期三天以上订单数："+four;
					 }
					 for(WeiXinPeopleBean weiXinPeopleBean:weiXinPeopleList) {
						 scheduleService.sendMessageUtilByOpenId(pp.getWorkShopName()+"车间拖期异常", weiXinPeopleBean,  "生产异常", dateString,soonDelay , RedirectUrlUtil.workshopDelay);
					 }
				 }
			 }
	    }
	}
	
	
	@RequestMapping("/getOrderDutySendMessage")
	@ResponseBody
	public void  getOrderDutySendMessage(String companyName){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String dateString=sdf.format(new Date());
		List<ProductionExceptionBean>  xx=orderMapper.getOrderTimerDelaySendMessage(companyName,1);
		List<ProductionExceptionBean>  yy=orderMapper.getOrderTimerDelaySendMessage(companyName,2);
		for(ProductionExceptionBean pp:yy) {
			List<String> userIdList=weChatToMessageService.getWeChatNewsUserIdListByParam(pp.getCompany(), null, null, "7");
			if(userIdList != null && userIdList.size()>0) {
				List<WeiXinPeopleBean> weiXinPeopleList=weiXinPeopleMapper.getWeiXinPeopleByUserIdList(userIdList);
				if(weiXinPeopleList != null && weiXinPeopleList.size()>0) {
					List<DutyBean> listDuty=pp.getListDuty();
					String soonDelay="";
					if(listDuty==null || listDuty.size()<=0) {
						soonDelay="恭喜您，没有即将拖期的订单";
					}else{
						soonDelay="十天内即将拖期的订单数："+listDuty.size();
					}
					for(WeiXinPeopleBean weiXinPeopleBean:weiXinPeopleList) {
						scheduleService.sendMessageUtilByOpenId("公司订单即将拖期提醒", weiXinPeopleBean,  "十天内将拖期异常", dateString, soonDelay, RedirectUrlUtil.queryOrder+"#dutyStatus=2&startDate=2017-01-01");
					}
				}
			}
		}
		
		for(ProductionExceptionBean pp:xx) {
			List<String> userIdList=weChatToMessageService.getWeChatNewsUserIdListByParam(pp.getCompany(), null, null, "7");
			if(userIdList != null && userIdList.size()>0) {
				List<WeiXinPeopleBean> weiXinPeopleList=weiXinPeopleMapper.getWeiXinPeopleByUserIdList(userIdList);
				if(weiXinPeopleList != null && weiXinPeopleList.size()>0) {
					List<DutyBean> listDuty=pp.getListDuty();
					int four=0;
					String soonDelay="";
					if(listDuty==null || listDuty.size()<=0) {
						soonDelay="恭喜您，没有拖期的订单";
					}else{
						for(DutyBean duty:listDuty) {
							four++;
						}
						soonDelay="拖期单数："+four;
					}
					for(WeiXinPeopleBean weiXinPeopleBean:weiXinPeopleList) {
						scheduleService.sendMessageUtilByOpenId("公司订单拖期提醒", weiXinPeopleBean,  "订单拖期异常", dateString,soonDelay , RedirectUrlUtil.queryOrder+"#dutyStatus=1&startDate=2017-01-01");
					}
				}
			}
		}
	}
	
	
	@RequestMapping("/getCapacitySendMessage")
	@ResponseBody
	public void  getCapacitySendMessage() throws ParseException{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String dateString=sdf.format(new Date());
		String day=TimeAndUnix.isToDayOrLastDay();
		List<ProductionExceptionBean>  xx=workshopMapper.getCapacitySendMessage(day);
		 for(ProductionExceptionBean pp:xx) {
			 List<String> userIdList=weChatToMessageService.getWeChatNewsUserIdListByParam(pp.getCompany(), pp.getDeptId(), pp.getWorkShopId(), "5");
			 if(userIdList != null && userIdList.size()>0) {
				 List<WeiXinPeopleBean> weiXinPeopleList=weiXinPeopleMapper.getWeiXinPeopleByUserIdList(userIdList);
				 for(WeiXinPeopleBean weiXinPeopleBean:weiXinPeopleList) {
					 scheduleService.sendMessageUtilByOpenId(pp.getWorkShopName()+"车间日产能提醒", weiXinPeopleBean,  "产能提醒", dateString,pp.getWorkShopName()+"车间"+day+"日产能为："+pp.getQualifiedCount() , RedirectUrlUtil.indexHtml);
				 }
			 }
		 }
	}
	
	
	
	@RequestMapping("/getMantissaSendMessage")
	@ResponseBody
	public void  getMantissaSendMessage() throws ParseException{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String dateString=sdf.format(new Date());
		List<ProductionExceptionBean>  xx=workshopMapper.getMantissaSendMessage();
		for(ProductionExceptionBean pp:xx) {
			List<String> userIdList=weChatToMessageService.getWeChatNewsUserIdListByParam(pp.getCompany(), pp.getDeptId(), pp.getWorkShopId(), "3");
			if(userIdList!= null && userIdList.size()>0) {
				List<WeiXinPeopleBean> weiXinPeopleList=weiXinPeopleMapper.getWeiXinPeopleByUserIdList(userIdList);
				if(weiXinPeopleList != null && weiXinPeopleList.size()>0) {
					List<DutyBean> listDuty=pp.getListDuty();
					String message="";
					if(listDuty==null || listDuty.size()<=0) {
						message="恭喜您，本车间没有尾数异常";
					}else {
						message="当前车间尾数异常条数为："+listDuty.size();
					}
					for(WeiXinPeopleBean weiXinPeopleBean:weiXinPeopleList) {
						scheduleService.sendMessageUtilByOpenId(pp.getWorkShopName()+"车间尾数异常", weiXinPeopleBean,  "生产异常", dateString,message , RedirectUrlUtil.workshopMantissa);
					}
				}
			}
		}
	}
	
	
	@RequestMapping("/getTurnoverSendMessage")
	@ResponseBody
	public void  getTurnoverSendMessage() throws ParseException{

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String dateString = sdf.format(new Date());
        List<ProductionExceptionBean> xx = workshopMapper.getTurnoverSendMessage();
        for (ProductionExceptionBean pp : xx) {
            List<String> userIdList = new ArrayList<String>();
            userIdList.add("566");
            if (userIdList != null && userIdList.size() > 0) {
                List<WeiXinPeopleBean> weiXinPeopleList = weiXinPeopleMapper.getWeiXinPeopleByUserIdList(userIdList);
                if (weiXinPeopleList != null && weiXinPeopleList.size() > 0) {
                    String message = pp.getWorkShopName() + "周转量:" + pp.getTurnover() + " ("
                            + pp.getWorkShopStartTurnover() + " ~ " + pp.getWorkShopEndTurnover() + ")";
                    if (pp.getTurnover() < pp.getWorkShopStartTurnover()) {
                        message = message + "  周转量过小";
                    } else if (pp.getTurnover() > pp.getWorkShopEndTurnover()) {
                        message = message + "  周转量过大";
                    } else {
                        message = message + "  周转量正常";
                    }
                    for (WeiXinPeopleBean weiXinPeopleBean : weiXinPeopleList) {
                    	scheduleService.sendMessageUtilByOpenId(pp.getWorkShopName() + "车间周转量", weiXinPeopleBean, "周转量提醒",
                                dateString, message, RedirectUrlUtil.turnover);
                    }
                }
            }
        }
    
	}
	
	@RequestMapping("/allMeaasge")
	@ResponseBody
	public void  allMeaasge() throws ParseException{
//		scheduleService.sendMessageByTardiness();
		scheduleService.getTimerDelaySendMessage();
		scheduleService.getCapacitySendMessage();
		scheduleService.getMantissaSendMessage();
		scheduleService.getTurnoverSendMessage();
	}
	
	
	
	@RequestMapping("/testParam")
	@ResponseBody
	public String   testParam(String param1,String param2) throws ParseException{
		return "success";
	}
	
	
	@RequestMapping("/testSetFeedDetail")
	@ResponseBody
	public String   testSetFeedDetail() throws ParseException{
		testService.testSetFeedDetail();
		return "success";
	}
	
	
	@RequestMapping("/testSetPurchaseDetail")
	@ResponseBody
	public String   testSetPurchaseDetail() throws ParseException{
		testService.testSetPurchaseDetail();
		return "success";
	}
	
	
	@RequestMapping("/testSetInOutDetail")
	@ResponseBody
	public String   testSetInOutDetail() throws ParseException{
		testService.testSetInOutDetail();
		return "success";
	}
	
	/**
	 * 发送邮件测试
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/testSendMail")
	@ResponseBody
	public String   testSendMail() throws Exception{
		String[] toAddrs= {"1432385148@qq.com"};
		
		String[] ccAddrs= {"1205540113@qq.com"};
		String subject="找回密码";
	    String htmlText="<a>点击链接找密码</a>";
		MailUtil.sendMailHtml(toAddrs,ccAddrs,subject,htmlText);
		return "success";
	}

	
	
	
	/**
	 * 发送邮件测试
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/setOrderSumFeed")
	@ResponseBody
	public String  setOrderSumFeed() throws Exception{
		testService.setOrderSumFeed();
		return "success";
	}
	
	
	
	@RequestMapping("/getCreateOrderCompany")
	@ResponseBody
	public void  getCreateOrderCompany() throws ParseException{
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//		String dateString=sdf.format(new Date());
//		List<String> companyList=workshopMapper.getReportCompany(dateString);
//		StringBuilder sb=new StringBuilder(dateString).append("报工公司");
//		for(String xx:companyList) {
//			sb.append("   ").append(xx);
//		}
//		//yechaobo
//		WeiXinPeopleBean weiXinPeopleBean=new WeiXinPeopleBean();
//		weiXinPeopleBean.setOpenid("o_THqw0u6q62kfSSW4YuBUOCUByc");
////		scheduleService.sendMessageUtilByOpenId("报工公司提醒", weiXinPeopleBean,  "报工公司提醒", dateString,sb.toString() , RedirectUrlUtil.reportCompany);
//		//nate
//		weiXinPeopleBean.setOpenid("o_THqw0_UhnWghEzp4DCHVZb23f8");
//		scheduleService.sendMessageUtilByOpenId("报工公司提醒", weiXinPeopleBean,  "报工公司提醒", dateString,sb.toString() , RedirectUrlUtil.reportCompany);
//		
//		
//		companyList=workshopMapper.getCreateOrderCompany(dateString);
//		sb=new StringBuilder(dateString).append("制单公司");
//		for(String xx:companyList) {
//			sb.append("   ").append(xx);
//		}
//		//yechaobo
//		weiXinPeopleBean.setOpenid("o_THqw0u6q62kfSSW4YuBUOCUByc");
////		scheduleService.sendMessageUtilByOpenId("制单公司提醒", weiXinPeopleBean,  "制单公司提醒", dateString,sb.toString() , RedirectUrlUtil.createOrderCompany);
//		//nate
//		weiXinPeopleBean.setOpenid("o_THqw0_UhnWghEzp4DCHVZb23f8");
		scheduleService.updateOneComapnyFinishOrderSort("铂亮光学");
	}

	
	
	
	
	
}
